import Vue from 'vue'
import VueRouter from 'vue-router'

import Register from '@/views/Register'
import Login from '@/views/Login'
import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
import Article from '@/views/Article'
import Collect from '@/views/Collect'
import Like from '@/views/Like'
import User from '@/views/User'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteLis = ['/login', '/register']

// 设置拦截守卫 => 前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机：每次页面跳转都会触发该函数
  // 只要注册了全局前置守卫，路由会立即瘫痪，必须要调用next()方法来放行
  // 参数1：t0到哪里去
  // 参数2：from从哪里来
  // 参数3：next函数，决定是否放行
  // next()表示放行，next('路径')表示强制跳转到指定路由，next(false)表示不放行
  const token = getToken()
  if (token) {
    next()
    // 以后白名单越来越多, 会导致写起来很麻烦
  } else {
    if (whiteLis.includes(to.path)) {
      next()
    } else {
      Toast.fail('你还未登录, 请登录!')
      next('/login')
    }
  }
})

export default router
